package com.cqs.learning.spring.cloud.producer.web.inteceptor;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * @Author lixw
 * @Date 6/6/20 12:32 AM
 */
@Slf4j
public class ReqInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setAttribute("traceId", UUID.randomUUID().toString());

        request.setAttribute("stopwatchStart", System.currentTimeMillis());
        MDC.put("traceId", (String) request.getAttribute("traceId"));
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Object startTime = request.getAttribute("stopwatchStart");
        if (startTime instanceof Long) {
            long cost = System.currentTimeMillis() - (long) startTime;
            log.info("耗时: {} 毫秒", cost);
        }
        MDC.remove("traceId");
    }
}
